/**
 * @author Rudy Kaplan Depena (The University of Texas at Austin)
 */
package com.utaustin.mirankerlab.ultrawrap.compiler.main;

import com.utaustin.mirankerlab.ultrawrap.compiler.exceptions.CommandLineException;
import com.utaustin.mirankerlab.ultrawrap.compiler.parser.Parser;
import com.utaustin.mirankerlab.ultrawrap.compiler.parser.syntaxtree.Query;
import com.utaustin.mirankerlab.ultrawrap.compiler.main.SparqlToSql;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;

/** Compiler begins execution here */
public class Main {
	
	public static void main(String[] args){
		
		//local variables
		boolean debug = false;
		String fileName = null;
		String inputString = null;
		InputStream is = null;
		
		//capture possibly bad input
		String possiblyBadInput = "";
		for(String arg : args){
			possiblyBadInput += arg + " ";
		}
		
		try{
			//if arguments, less than 2, then bad input, so throw exceptions
			if(args.length < 2){ throw new CommandLineException(possiblyBadInput);}
			
			//search through arguments
			for(int i = 0; i < args.length; ++i){//iterate thru arguments
				if(args[i].equals("-f")){//if -f is found, then file is expected
					//make sure there is file name after words and no input string
					//remember we cannot process a file and a string at the same time
					if(i+1 < args.length && inputString == null){ fileName = args[i+1]; }
					else{ throw new CommandLineException(possiblyBadInput); }
				}
				else if(args[i].equals("-d")){//if -d is found, then enter debug mode
					debug = true;
				}
				else if(args[i].equals("-s")){//if -s is found, then input string expected
					//make sure there is an input string after words and no file name
					//remember we cannot process a file and a string at the same time
					if(i+1 < args.length && fileName == null){ inputString = args[i+1]; }
					else{ throw new CommandLineException(possiblyBadInput); }
				}
			}
			
			//execute commands from arguments
			//if input string, then set input stream with string
			if(inputString != null){ is = new ByteArrayInputStream(inputString.getBytes("UTF-8")); }
			//if file name, then set input stream with file
			else if(fileName != null){ is = new FileInputStream(new File(fileName)); }
			//if input stream is still null, then throw exception
			if(is == null){ throw new CommandLineException(possiblyBadInput); }
			Parser parser = new Parser(is);//feed parser the input stream data
			Query query = parser.Query();//return root node of syntax tree
			//create visitor that is used to traverse tree starting at root 
			SparqlToSql sparql2sql = new SparqlToSql(debug);
			//walk the tree with the visitor,sparqlToSql
			query.accept(sparql2sql);
			
		}
		catch(Exception e){e.printStackTrace();}
		
	}

}
